package app.database.friendlist;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.example.server.SCSocketComm;
import com.example.silvercare.Coalition;
import com.example.silvercare.R;
import com.example.silvercare.Setting;
import com.example.silvercare.UserInputCheck;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Friend extends Activity {
	EditText nameET, emailET;
	Button submitBT;
	FriendListDB dba;
	int TABLE;
	String NAME;
	String EMAIL;
	
	String name = "";
	String email = "";
	
    String IpAddress;
    String Port;
    
    SharedPreferences myprefs;
    String myname;
    String myemail;
  
	final Handler UpdateHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {      
		             case 1:
		            	 Toast.makeText(Friend.this, "Connection failed or Rejected by friend", Toast.LENGTH_SHORT).show();
		                  break;   
		             case 2:
		     			Toast.makeText(Friend.this, "Email Address Already Exist In Database", Toast.LENGTH_SHORT).show();
		     			break;
		             case 3:
		     			nameET.setText("");
		    			emailET.setText("");
		     			Toast.makeText(Friend.this, "Item Saved", Toast.LENGTH_SHORT).show();		
		     			break;
		              }      
		              super.handleMessage(msg);  
		         }    
		     }; 
		     
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.xml.friend);
		
		dba = new FriendListDB(this);
		dba.open();
		
        myprefs = PreferenceManager.getDefaultSharedPreferences(this);
        myname = myprefs.getString("namePref", null);
        myemail = myprefs.getString("emailaddressPref", null);
        
		TABLE = getIntent().getIntExtra("TABLE", -1);
		NAME = getIntent().getStringExtra("NAME");
		EMAIL = getIntent().getStringExtra("EMAIL");
		name = NAME;
		email = EMAIL;
		if(TABLE == -1)
		{
			Toast.makeText(this, "Table not selected in database", Toast.LENGTH_SHORT).show();
			onDestroy();
		}
		
		
		nameET = (EditText) findViewById(R.id.friendnameText);
		emailET = (EditText) findViewById(R.id.emailaddressText);
		submitBT = (Button) findViewById(R.id.addfriendButton);
		
		nameET.setText(name);
		emailET.setText(email);
		
		if(NAME==null && EMAIL == null)
			//ADD FRIEND
			submitBT.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					try{
						//input check
						name = nameET.getText().toString();
						email = emailET.getText().toString();
						final String checkName = UserInputCheck.nameCheck(name);
						final String checkEmail = UserInputCheck.emailaddressCheck(email);
						if(checkName != null && checkEmail != null)
						{
							Toast.makeText(Friend.this, "Don't close, Waiting for your friend response", Toast.LENGTH_SHORT).show();
							Thread bgThread = new Thread(new Runnable(){

								@Override
								public void run() {
									// TODO Auto-generated method stub
									if(checkPermission(checkName, checkEmail))
										saveItToDB(checkName, checkEmail, "", "", TABLE);
									else{
										 Message message = new Message();      
										 message.what = 1;      
										 UpdateHandler.sendMessage(message); 
									}
								}
								
							});
							bgThread.start();

						}
						else
							Toast.makeText(Friend.this, "Input Invalid or Null", Toast.LENGTH_SHORT).show();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				
			});
		else
			//EDIT FRIEND(out-of-date)
			submitBT.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					try{
						//input check
						name = nameET.getText().toString();
						email = emailET.getText().toString();
						String checkName = UserInputCheck.nameCheck(name);
						String checkEmail = UserInputCheck.emailaddressCheck(email);
						if(checkName != null && checkEmail != null)
							updateItToDB(checkName, checkEmail, "", "", EMAIL, TABLE);
						else
							Toast.makeText(Friend.this, "Input Invalid or Null", Toast.LENGTH_SHORT).show();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				
			});			
	}
	
	public boolean checkPermission(String name, String email){
		if(getFriendConnectionInfo(email)==0)
		{
			 try {
	                Socket socket = new Socket(IpAddress,Integer.parseInt(Port));
	                //outgoing stream redirect to socket
	                message.Message msg1 = new message.Message();
	                msg1.setServiceType(1);
	                msg1.setContent(myname+"|"+myemail);
	                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
	                oos.writeObject(msg1);
	                
	                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
	                message.Message msg2 = (message.Message) ois.readObject();
	                
	                //Close connection
	                socket.close();
	                
	                if(msg2.getContent()!=null)
	                {
	                	Log.d("Tcp Example", "From server: "+msg2.getContent());
	                	if(msg2.getContent().contentEquals("YES"))
	                		return true;
	                	else
	                		return false;
	                }
	                else
	                {
	                	Log.d("Tcp Example", "From server: "+"null");
	                	return false;
	                }
	        		


		        } catch (UnknownHostException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return false;
		
	}
	
	//Request Ip address and port throught Coalition
	private int getFriendConnectionInfo(String email){
		String result = Coalition.getFriendConnectionInfo(email);
		if(result==null || !result.contains("|"))
			return -1;
		int mid = result.indexOf("|");
		String s1 = result.substring(0, mid);
		String s2 = result.substring(mid+1, result.length());
		if(s1 == null || s2 == null)
			return -1;
		IpAddress = s1;
		Port = s2;	
		return 0;
	}
	
	public void saveItToDB(String name, String email, String notification, String notificationDate, int table){
		if(dba.insertFriend(name, email, notification, notificationDate, table)==-1)
		{
			 Message message = new Message();      
			 message.what = 2;      
			 UpdateHandler.sendMessage(message); 

		}else
		{
			 Message message = new Message();      
			 message.what = 3;      
			 UpdateHandler.sendMessage(message); 

			dba.close();

			finish();  
		}
		/*
		if(table==0)
			startActivity(new Intent("com.example.server.FriendListActivity"));
		else if(table==1)
			startActivity(new Intent("com.example.server.TrustFriendsActivity"));*/
	}
	
	public void updateItToDB(String name, String email, String notification, String notificationDate, String oldemail, int table){
		if(dba.updateFriend(name, email, notification, notificationDate, oldemail,  table)==-1)
			Toast.makeText(Friend.this, "Email Address Already Exist In Database", Toast.LENGTH_SHORT).show();
		else
		{
			Toast.makeText(this, "Item Updated", Toast.LENGTH_SHORT).show();		
			dba.close();
			nameET.setText("");
			emailET.setText("");

			finish();  
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		dba.close();
		super.onDestroy();
	}
}
